<?php
/**
 * Created by PhpStorm.
 * User: g
 * Date: 2017/4/19
 * Time: 16:24
 */

namespace app\home\controller;
use app\common\controller\Homebase;
use think\Db;

class Dictionary extends Basic
{
    public function _initialize()
    {
        parent::_initialize();
        $arr[0]['text']='字典列表';
        $arr[0]['url']='index';
        $this->assign('third_menu', $arr);
    }

    public function index(){
        $record = db("dictionary")->paginate(15);
        $this->assign("record",$record);
        return $this->fetch();
    }

    public function add(){
        if(IS_POST){
            $data = input('');
            $flag = db('dictionary')->insert($data);
            if($flag){
                return $this->ret->setCode(0)->setMsg("保存成功")->setAsk("保存成功，是否继续？")->toJson();
            }else{
                return $this->ret->setCode(1)->setMsg("保存失败，请重试")->toJson();
            }
        }else{
            return $this->fetch();
        }
    }

    public function edit(){
        $dict_value = input('dv');
        $records = db("dict_data")
            ->where("dict_value",$dict_value)
            ->order("sort desc")
            ->select();
        $this->assign("records",$records);
        return $this->fetch();
    }

    public function editDict(){
        $dict_value = input("dict_value");
        $dict_data_list = input('dict_data/a');
        Db::startTrans();
        db('dict_data')->where('dict_value',$dict_value)->delete();
        //db('dict_data')->insertAll($dict_data_list);
        foreach ($dict_data_list as $dict_data){
            db('dict_data')->data($dict_data)->insert();
        }
        Db::commit();
        return $this->ret->setCode(0)->setMsg("修改成功")->toJson();

    }

    public function del($id){
        $flag = db('dictionary')->where('id',$id)->delete();
        if($flag){
            $this->success("删除成功",url('index'));
        }else{
            $this->error("删除失败",url('/index'));
        }

    }
}